package com.utils;

import sun.net.www.http.ChunkedOutputStream;

import java.io.*;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by full on 2018/4/26.
 */
public class ZipUtil {

    static Logger log = Logger.getLogger("zipUtil");

    private static final int BUFSIZE = 1024;

    public static void zip(String srcPath, String zipFilePath) {

        File srcFilePath = new File(srcPath);

        if (!srcFilePath.exists()) {
            throw new RuntimeException(srcPath + "不存在");
        }

        File zipFile = new File(zipFilePath);

        try {

            FileOutputStream fos = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());
            ZipOutputStream zos = new ZipOutputStream(cos);
            String baseDir = "";
            int deep = 0;
            compressbyType(srcFilePath, zos, baseDir,deep);
            zos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private static void compressbyType(File srcPath, ZipOutputStream zos, String baseDir,int deep) {

        if (!srcPath.exists())
            return;

        log.info("压缩" + baseDir + srcPath.getName());

        if (srcPath.isFile()) {
            compressFile(srcPath, zos, baseDir);
        } else if (srcPath.isDirectory()) {
            compressDir(srcPath, zos, baseDir,deep);
        }
    }

    /**
     * 压缩文件
     */
    private static void compressFile(File file, ZipOutputStream zos, String baseDir) {
        if (!file.exists())
            return;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(baseDir + file.getName());
            zos.putNextEntry(entry);
            int count;
            byte[] buf = new byte[BUFSIZE];
            while ((count = bis.read(buf)) != -1) {
                zos.write(buf, 0, count);
            }
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩文件夹
     */
    private static void compressDir(File dir, ZipOutputStream zos, String baseDir,int deep) {
        if (!dir.exists())
            return;
        File[] files = dir.listFiles();
        if(files.length == 0){
            try {
                zos.putNextEntry(new ZipEntry(baseDir + dir.getName() + File.separator));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        deep++;
        for (File file : files) {
            if (deep == 1) {
                compressbyType(file, zos, baseDir+"", deep);
            } else {

                compressbyType(file, zos, baseDir + dir.getName() + File.separator,deep);
            }
        }
    }
}